package org.jeecg.modules.artice.controller;


import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.http.HtmlUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.wanghaomiao.xpath.exception.NoSuchAxisException;
import cn.wanghaomiao.xpath.exception.NoSuchFunctionException;
import cn.wanghaomiao.xpath.exception.XpathSyntaxErrorException;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sudytech.cms.ws.client.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.content.entity.ContentGoto;
import org.jeecg.modules.content.service.IContentGotoService;
import org.jeecg.modules.content.service.IContentInfoService;
import org.jeecg.modules.crawler.entity.NewCrawlerInfo;
import org.jeecg.modules.task.entity.TaskOutLink;
import org.jeecg.modules.task.service.ITaskOutLinkService;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.net.ssl.HttpsURLConnection;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.*;

import static java.lang.System.out;

@Slf4j
@Api(tags="添加新闻网")
@RestController
@RequestMapping("/third/news")
public class ArticleDataController {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IContentInfoService conContentInfoService;
    @Autowired
    private IContentGotoService contentGotoService;
    @Autowired
    ITaskOutLinkService outLinkService;

    @SneakyThrows
    @AutoLog(value = "同步文章")
    @ApiOperation(value="同步文章", notes="同步文章")
    @PostMapping(value = "/add")
    public Result<?> syncArticle(@RequestBody Map<String,Object> reqMap) throws SQLException {
//        String domainId="210"; //需要提供
        String domainId="95";
        if(!StringUtils.isEmpty(reqMap.get("domainId"))){
            domainId = reqMap.get("domainId").toString();
        }
         //需要提供

//        Long folderId = 11393L;//需要提供
        Long folderId = Long.parseLong(reqMap.get("folderId").toString());//需要提供

        try {
//            String id = reqMap.get()
//            ConContentInfo conContentInfo = conContentInfoService.getById(id);
//
            Object key = redisUtil.get(reqMap.get("contentTitle").toString());
            if(key != null){
                return Result.ok("成功");
            }
            CmsWebService_ServiceLocator serviceLocator = new CmsWebService_ServiceLocator();
//            CmsWebService_PortType portType = serviceLocator.getCmsWebServicePort(new URL("http://101.201.151.238/_wp3services/CmsWebService"));
            CmsWebService_PortType portType = serviceLocator.getCmsWebServicePort(new URL("http://webplus.seu.edu.cn/_wp3services/CmsWebService"));

            String token = encryptSecureToken();
//            String domainId = "75";//站点id 75
            ArticleSO articleSO = new ArticleSO();
            articleSO.setTitle(!StringUtils.isEmpty(reqMap.get("contentTitle"))?reqMap.get("contentTitle").toString():"");//标题
            articleSO.setCreateTime(Calendar.getInstance());//撰写日期
            if(!StringUtils.isEmpty(reqMap.get("content")))
            {
                String summary = reqMap.get("contentIntroduce") != null ? reqMap.get("contentIntroduce").toString() : "";
                if(StringUtils.isEmpty(summary)){
                    summary  = HtmlUtil.cleanHtmlTag(reqMap.get("content").toString());
                }
                articleSO.setSummary(summary.length()<200 ? summary: summary.substring(0,199));//标题
            }

            articleSO.setSource("");//来源
            articleSO.setCreateOrgName("");//创建机构名称
//            articleSO.setLinkUrl("www.baidu.com");//外链
            PublishStatusSO publishStatusSO = new PublishStatusSO();
            publishStatusSO.setOpened(true);
            publishStatusSO.setPublished(true);
            publishStatusSO.setPublishTime(Calendar.getInstance());
            articleSO.setPublishStatus(publishStatusSO);

            //文章内容：数组大小表示内容的分页数，这里2表示文章内容有两页
            String content = reqMap.get("content").toString();
            if(!content.contains("_ueditor_page_break_tag_")){
                ArticleContent[] contents = new ArticleContent[1];
                ArticleContent page1Content = new ArticleContent();
                page1Content.setContent(reqMap.get("content").toString());
                contents[0] = page1Content;//文章的第一页内容
                articleSO.setFetchArticleContent(contents);
            }else{
                String[]  contentArray = content.split("_ueditor_page_break_tag_");
                ArticleContent[] contents = new ArticleContent[contentArray.length];
                for(int i = 0 ; i < contentArray.length ; i++){
                    ArticleContent pageContent = new ArticleContent();
                    pageContent.setContent(contentArray[i]);
                    contents[i] = pageContent;
                }
                articleSO.setFetchArticleContent(contents);
            }

            //查询外链
            String taskNo = reqMap.get("taskNo").toString();
            QueryWrapper<TaskOutLink> outLinkQueryWrapper = new QueryWrapper<>();
            outLinkQueryWrapper.eq("task_no",taskNo);
            List<TaskOutLink>  outLinkList = outLinkService.list(outLinkQueryWrapper);
            if(null != outLinkList && outLinkList.size() > 0 && !StringUtils.isEmpty(outLinkList.get(0))){
                articleSO.setLinkUrl(outLinkList.get(0).getUrl().toString());
            }
            articleSO.setTypeName("basicFolder");

            try{
                List<Map<String,Object>> contentAdditionList  =  (List<Map<String,Object>>)reqMap.get("contentAddition");
                if(null != contentAdditionList && contentAdditionList.size() > 0){
                    for(int i= 0;i<contentAdditionList.size();i++){
                        if(i == 0){
                            articleSO.setField1(contentAdditionList.get(i).get("attachContent").toString());
                        }else if(i == 1){
                            articleSO.setField2(contentAdditionList.get(i).get("attachContent").toString());
                        }else if(i == 2){
                            articleSO.setField3(contentAdditionList.get(i).get("attachContent").toString());
                        }
                    }
//                    articleSO.setTypeName();
                    if(folderId == 26930){
                        articleSO.setTypeName("35");
                    }else if(folderId == 26938 || folderId == 26939 || folderId == 26940 || folderId ==45644 ){
                        articleSO.setTypeName("33");
                    }else if(folderId == 45795){
                        articleSO.setTypeName("29");
                    }else if(folderId == 45776){
                        articleSO.setTypeName("34");
                    }else if(folderId == 45796){
                        articleSO.setTypeName("33");
                    }
                }


            }catch (Exception e){
                e.printStackTrace();
            }
            //封装文章内容中出现的附件，需要将附件流化，附件包含图片、文档等等，这里上面内容中出现了两个附件需要处理
            ArticleSOAttachmentMap map = new ArticleSOAttachmentMap();//封装附件的总对象
            List<ArticleSOAttachmentMapEntry> entrys = new ArrayList<ArticleSOAttachmentMapEntry>();//这里有两张图片，那么这个list的大小是2
//            ArticleSOAttachmentMapEntry imgEntry1 = new ArticleSOAttachmentMapEntry();
//            imgEntry1.setKey("/_tempxx/测试word文档.docx");//这里是文章内容中附件的路径，这里附件1的路径是：/_tempxx/测试word文档.docx
//            String img1RealPath = "F:\\运维\\苏职大\\webService附件\\测试word文档.docx";//附件1的绝对路径
//            imgEntry1.setValue(FileUtil.readBytes(img1RealPath));//这里是将图片流化后的Byte数组,这个FileUtil.readBytes作用是读取附件并流化，流化方法自己写一个
//            entrys.add(imgEntry1);
//            ArticleSOAttachmentMapEntry imgEntry2 = new ArticleSOAttachmentMapEntry();
//            imgEntry2.setKey("/_tempxx/Apache反向代理.pdf");//这里是文章内容中附件的路径，这里附件2的路径是：/_tempxx/Apache反向代理.pdf
//            String img2RealPath = "F:\\运维\\苏职大\\webService附件\\Apache反向代理.pdf";//附件2的绝对路径
//            imgEntry2.setValue(FileUtil.readBytes(img2RealPath));
//            entrys.add(imgEntry2);
//            map.setEntry(entrys.toArray(new ArticleSOAttachmentMapEntry[entrys.size()]));
//            articleSO.setAttachmentMap(map);


            //设置封面
            if(!StringUtils.isEmpty(reqMap.get("banner"))){
                articleSO.setFirstImgName(reqMap.get("banner").toString().split("/")[reqMap.get("banner").toString().split("/").length-1]);
                ArticleSOAttachmentMapEntry firstImgEntry = new ArticleSOAttachmentMapEntry();
                firstImgEntry.setKey(reqMap.get("banner").toString().split("/")[reqMap.get("banner").toString().split("/").length-1]);//这里是文章内容中附件的路径，这里附件2的路径是：/_tempxx/Apache反向代理.pdf
//            String firstImgRealPath = "C:\\Users\\yuanl\\Desktop\\20230922 (3)\\1625131923050.jpg";//附件2的绝对路径
                firstImgEntry.setValue(onlineImage2byte(reqMap.get("banner").toString()));
                entrys.add(firstImgEntry);
                map.setEntry(entrys.toArray(new ArticleSOAttachmentMapEntry[entrys.size()]));
                articleSO.setAttachmentMap(map);
            }else{
                map.setEntry(entrys.toArray(new ArticleSOAttachmentMapEntry[entrys.size()]));
                articleSO.setAttachmentMap(map);
            }


            //设置文章创建人名称
            User user = new User();
            user.setName(!StringUtils.isEmpty(reqMap.get("authorName"))?reqMap.get("authorName").toString():"");//标题

            //创建文章，状态为草稿，返回职位创建的文章id
            long articleId = portType.createArticle(token, domainId, user, folderId, articleSO);
            long[] articleIds = new long[]{articleId};
            portType.publishArticle(token, domainId, user, articleIds, publishStatusSO);

            System.out.println("增加文章成功，打印id:" + articleId);
//            out.write(alertLoginErrorMessage("增加文章成功，文章id:" + articleId, "addArticle"));

            //发布-------------------------
//        long[] articleIds = new long[]{articleId};//所需发布的文章id数组
//        //文章发布属性 必要字段为open、published,没有特殊情况open为true，如果有浏览组则open为false  如果发布但不对外公布则published为false 如果对外公布则为true
//        //其他发布属性参照文档 按需填写
//        PublishStatusSO publishStatus = new PublishStatusSO();
//        publishStatus.setOpened(true);
//        publishStatus.setPublished(true);
//        portType.publishArticle(token, domainId, user, articleIds, publishStatus);
//        out.write(alertLoginErrorMessage("张三在网站群站点:" + domainId + "下发布文章：" + Arrays.toString(articleIds), "publishArticle"));


            ContentGoto contentGoto = new ContentGoto();
            contentGoto.setId(UUIDGenerator.generate());
            contentGoto.setContent_id(reqMap.get("contentNo").toString());
            contentGoto.setDest(domainId.equals("95")?3:2);
            contentGotoService.save(contentGoto);
        }  catch (Exception e) {
            e.printStackTrace();
            return Result.error("发送失败");
//            out.write(alertLoginErrorMessage("增加文章出错:" + e.getMessage(), "addArticle"));
        }
        return  Result.ok("成功");
    }



    @SneakyThrows
    @AutoLog(value = "同步文章")
    @ApiOperation(value="同步文章", notes="同步文章")
    @PostMapping(value = "/add2")
    public Result<?> syncArticle2(@RequestBody Map<String,Object> reqMap) throws SQLException {
//        String domainId="210"; //需要提供
        String domainId="95";
        if(!StringUtils.isEmpty(reqMap.get("domainId"))){
            domainId = reqMap.get("domainId").toString();
        }
        //需要提供

//        Long folderId = 11393L;//需要提供
        Long folderId = Long.parseLong(reqMap.get("folderId").toString());//需要提供

        try {
//            String id = reqMap.get()
//            ConContentInfo conContentInfo = conContentInfoService.getById(id);
//
            Object key = redisUtil.get(reqMap.get("contentTitle").toString());
            if(key != null){
                return Result.ok("成功");
            }

            String title = reqMap.get("contentTitle").toString();
            List<NewCrawlerInfo> crawlerInfos = getUrlByContent(title);//从爬虫找
            if(crawlerInfos ==null ||crawlerInfos.size() !=1){
                return Result.error("查询到文章：《"+title+"》在新闻网无发布链接或查询到多条记录，请联系管理员查询");
            }
            String url = crawlerInfos.get(0).getLink();
            CmsWebService_ServiceLocator serviceLocator = new CmsWebService_ServiceLocator();
//            CmsWebService_PortType portType = serviceLocator.getCmsWebServicePort(new URL("http://101.201.151.238/_wp3services/CmsWebService"));
            CmsWebService_PortType portType = serviceLocator.getCmsWebServicePort(new URL("http://webplus.seu.edu.cn/_wp3services/CmsWebService"));

            String token = encryptSecureToken();
//            String domainId = "75";//站点id 75
            ArticleSO articleSO = new ArticleSO();
            articleSO.setTitle(!StringUtils.isEmpty(reqMap.get("contentTitle"))?reqMap.get("contentTitle").toString():"");//标题
            articleSO.setCreateTime(Calendar.getInstance());//撰写日期
            if(!StringUtils.isEmpty(reqMap.get("content")))
            {
                String summary = reqMap.get("contentIntroduce") != null ? reqMap.get("contentIntroduce").toString() : "";
                if(StringUtils.isEmpty(summary)){
                    summary  = HtmlUtil.cleanHtmlTag(reqMap.get("content").toString());
                }
                articleSO.setSummary(summary.length()<200 ? summary: summary.substring(0,199));//标题
            }

            articleSO.setSource("");//来源
            articleSO.setCreateOrgName("");//创建机构名称
//            articleSO.setLinkUrl("www.baidu.com");//外链
            PublishStatusSO publishStatusSO = new PublishStatusSO();
            publishStatusSO.setOpened(true);
            publishStatusSO.setPublished(true);
            publishStatusSO.setPublishTime(Calendar.getInstance());
            articleSO.setPublishStatus(publishStatusSO);

            //查询外链
                articleSO.setLinkUrl(url);
            articleSO.setTypeName("basicFolder");


            //封装文章内容中出现的附件，需要将附件流化，附件包含图片、文档等等，这里上面内容中出现了两个附件需要处理
            ArticleSOAttachmentMap map = new ArticleSOAttachmentMap();//封装附件的总对象
            List<ArticleSOAttachmentMapEntry> entrys = new ArrayList<ArticleSOAttachmentMapEntry>();//这里有两张图片，那么这个list的大小是2

            //设置封面
            if(!StringUtils.isEmpty(reqMap.get("banner"))){
                articleSO.setFirstImgName(reqMap.get("banner").toString().split("/")[reqMap.get("banner").toString().split("/").length-1]);
                ArticleSOAttachmentMapEntry firstImgEntry = new ArticleSOAttachmentMapEntry();
                firstImgEntry.setKey(reqMap.get("banner").toString().split("/")[reqMap.get("banner").toString().split("/").length-1]);//这里是文章内容中附件的路径，这里附件2的路径是：/_tempxx/Apache反向代理.pdf
//            String firstImgRealPath = "C:\\Users\\yuanl\\Desktop\\20230922 (3)\\1625131923050.jpg";//附件2的绝对路径
                firstImgEntry.setValue(onlineImage2byte(reqMap.get("banner").toString()));
                entrys.add(firstImgEntry);
                map.setEntry(entrys.toArray(new ArticleSOAttachmentMapEntry[entrys.size()]));
                articleSO.setAttachmentMap(map);
            }else{
                map.setEntry(entrys.toArray(new ArticleSOAttachmentMapEntry[entrys.size()]));
                articleSO.setAttachmentMap(map);
            }


            //设置文章创建人名称
            User user = new User();
            user.setName(!StringUtils.isEmpty(reqMap.get("authorName"))?reqMap.get("authorName").toString():"");//标题

            //创建文章，状态为草稿，返回职位创建的文章id
            long articleId = portType.createArticle(token, domainId, user, folderId, articleSO);
            long[] articleIds = new long[]{articleId};
            portType.publishArticle(token, domainId, user, articleIds, publishStatusSO);

            System.out.println("增加文章成功，打印id:" + articleId);
//            out.write(alertLoginErrorMessage("增加文章成功，文章id:" + articleId, "addArticle"));

            //发布-------------------------
//        long[] articleIds = new long[]{articleId};//所需发布的文章id数组
//        //文章发布属性 必要字段为open、published,没有特殊情况open为true，如果有浏览组则open为false  如果发布但不对外公布则published为false 如果对外公布则为true
//        //其他发布属性参照文档 按需填写
//        PublishStatusSO publishStatus = new PublishStatusSO();
//        publishStatus.setOpened(true);
//        publishStatus.setPublished(true);
//        portType.publishArticle(token, domainId, user, articleIds, publishStatus);
//        out.write(alertLoginErrorMessage("张三在网站群站点:" + domainId + "下发布文章：" + Arrays.toString(articleIds), "publishArticle"));


            ContentGoto contentGoto = new ContentGoto();
            contentGoto.setId(UUIDGenerator.generate());
            contentGoto.setContent_id(reqMap.get("contentNo").toString());
            contentGoto.setDest(domainId.equals("95")?3:2);
            contentGotoService.save(contentGoto);
        }  catch (Exception e) {
            e.printStackTrace();
            return Result.error("发送失败");
//            out.write(alertLoginErrorMessage("增加文章出错:" + e.getMessage(), "addArticle"));
        }
        return  Result.ok("成功");
    }


    private List<NewCrawlerInfo> getUrlByContent(String keyword) {
        String queryStr = "[{\"field\":\"pageIndex\",\"value\":"+1+"},{\"field\":\"group\",\"value\":0},{\"field\":\"searchType\",\"value\":\"\"},{\"field\":\"keyword\",\"value\":\"" + keyword + "\"},{\"field\":\"recommend\",\"value\":\"1\"},{\"field\":4,\"value\":\"\"},{\"field\":5,\"value\":\"\"},{\"field\":6,\"value\":\"\"},{\"field\":7,\"value\":\"\"}]";
        String query = Base64Encoder.encode(queryStr.getBytes(StandardCharsets.UTF_8));
        List<NewCrawlerInfo> crawlerInfos = new ArrayList<>();
        try {

            Map<String, Object> fromMap = new HashMap<>();
            fromMap.put("searchInfo", query);
            HttpRequest post = HttpUtil.createPost("https://www.seu.edu.cn/_web/_search/api/searchCon/create.rst?_p=YXM9MiZ0PTI0OTImZD05NTk1JnA9MSZtPVNOJg__&tt=" + Math.random());
            post.header("Referer", "https://www.seu.edu.cn/_web/_search/api/search/new.rst?locale=zh_CN&request_locale=zh_CN&_p=YXM9MiZ0PTI0OTImZD05NTk1JnA9MSZtPVNOJg__");
            post.form(fromMap);
            HttpResponse httpResponse = post.execute();
            JSONObject respObj = (JSONObject) JSONObject.parse(httpResponse.body());
            String respStr = respObj.getString("data");
            String xpath = "//html/body/div";
            JXDocument jxDocument = new JXDocument(respStr);
            List<Object> rs = jxDocument.sel(xpath);
            for (Object o : rs) {
                if (o instanceof Element) {
                    NewCrawlerInfo tempInfo = new NewCrawlerInfo();
                    //链接
                    String aStr = ((Element) o).outerHtml();
                    String apath = "//html/body/div/h3/a/@href";
                    JXDocument aJxDocument = new JXDocument(aStr);
                    List<Object> ars = aJxDocument.sel(apath);
//                        System.out.println(ars.get(0).toString());
                    tempInfo.setLink(ars.get(0).toString());
                    //标题
                    String titleStr = ((Element) o).outerHtml();
                    String titlepath = "//html/body/div/h3/a";
                    JXDocument titleJxDocument = new JXDocument(titleStr);
                    List<Object> titlers = titleJxDocument.sel(titlepath);
                    Object titleO = titlers.get(0);
                    String title = ((Element) titleO).html();
//                        System.out.println(title);
                    tempInfo.setTitle(title);
                    tempInfo.setId(title);
                    //其他信息 创建者，发布时间，目录 ，出处
                    String otherStr = ((Element) o).outerHtml();
                    String otherpath = "//html/body/div/span";
                    JXDocument otherJxDocument = new JXDocument(otherStr);
                    List<Object> otherrs = otherJxDocument.sel(otherpath);
                    if (otherrs.size() >= 1) {
                        Object otherO1 = otherrs.get(0);
                        tempInfo.setAuthor(((Element) otherO1).html());
                    }
                    if (otherrs.size() >= 2) {
                        Object otherO2 = otherrs.get(1);
                        tempInfo.setTime(((Element) otherO2).html().replaceAll("发布时间:", ""));
                    }
                    if (otherrs.size() >= 3) {
                        Object otherO3 = otherrs.get(2);
                        tempInfo.setMl(((Element) otherO3).html());
                    }
                    if (otherrs.size() >= 4) {
                        Object otherO4 = otherrs.get(3);
                        tempInfo.setSource(((Element) otherO4).html());
                    }
                    if (tempInfo.getSource().contains("新闻网")) {
                        crawlerInfos.add(tempInfo);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return crawlerInfos;
    }

    public static byte[] onlineImage2byte(String path) throws IOException {
        byte[] data = null;
        URL url = null;
        InputStream input = null;
        try{
            url = new URL(path);
            HttpsURLConnection httpUrl = (HttpsURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            input = httpUrl.getInputStream();
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int numBytesRead = 0;
        while ((numBytesRead = input.read(buf)) != -1) {
            output.write(buf, 0, numBytesRead);
        }
        data = output.toByteArray();
        output.close();
        input.close();
        return data;
    }

    /**
     * 同步文章
     *
     * @return
     */
//    @AutoLog(value = "同步文章")
//    @ApiOperation(value="同步文章", notes="同步文章")
//    @GetMapping(value = "/syncArticle")
//    public Result<?> syncArticle(@RequestParam(name = "id")String id) throws SQLException {
//        String endpoint = "http://47.104.9.219:80/_wp3services/CmsWebService?xsd=1";
//        Service service = new Service();
//        try {
//            Call call = (Call) service.createCall();
//            QName qn = new QName("http://impl.ws.cms.sudytech.com/","createArticle");
//            call.setTargetEndpointAddress(new java.net.URL(endpoint));
////            call.setSOAPActionURI("http://47.104.9.219:80/_wp3services/CmsWebService/createArticle");
//            call.setOperationName(qn);
////            call.setOperation("createArticle");
//            call.addParameter("loginToken", XMLType.XSD_STRING, ParameterMode.IN);
//            call.addParameter("domainId", XMLType.XSD_STRING, ParameterMode.IN);
//            call.addParameter("user", XMLType.XSD_STRING, ParameterMode.IN);
//            call.addParameter("folderId", XMLType.XSD_LONG, ParameterMode.IN);
//            call.addParameter("article",XMLType.XSD_ANYTYPE,ArticleSO.class, ParameterMode.IN);
//            call.registerTypeMapping(ArticleSO.class,   qn,
//                    new BeanSerializerFactory(ArticleSO.class,   qn),
//                    new BeanDeserializerFactory(ArticleSO.class,   qn));
//
//            call.registerTypeMapping(PublishStatusSo.class,   qn,
//                    new BeanSerializerFactory(PublishStatusSo.class,   qn),
//                    new BeanDeserializerFactory(PublishStatusSo.class,   qn));
//
//
//            call.registerTypeMapping(User.class,   qn,
//                    new BeanSerializerFactory(User.class,   qn),
//                    new BeanDeserializerFactory(User.class,   qn));
//
////
//            call.registerTypeMapping(ArticleContent.class,   qn,
//                    new BeanSerializerFactory(ArticleContent.class,   qn),
//                    new BeanDeserializerFactory(ArticleContent.class,   qn));
//
////
//            call.setReturnType(XMLType.XSD_LONG);
//            String loginToken = encryptSecureToken();
//            String domainId="210"; //需要提供
////            user.setName("系统管理员");
//            Long folderId = 11393L;//需要提供
//
//            ArticleSO articleSO = new ArticleSO();
//            articleSO.setTitle("oa对接测试1");//标题
//            articleSO.setSummary("这是文章摘要/简介");//简介
//            articleSO.setSource("测试");//来源
//            articleSO.setCreateOrgName("测试");//创建机构名称
//            articleSO.setPublishStatus(new PublishStatusSo());
//
////            //文章内容：数组大小表示内容的分页数，这里2表示文章内容有两页
//            ArticleContent[] contents = new ArticleContent[2];
//            ArticleContent page1Content = new ArticleContent();
//            page1Content.setContent("这是第一页里面的内容：这是一条用于测试webService对接-新增文章！请不必惊慌！<img src=\"/_ueditor/themes/default/images/icon_doc.gif\" /><a href=\"/_tempxx/测试word文档.docx\" sudyfile-attr=\"{'title':'测试word文档.docx'}\">测试word文档.docx</a>");
//            contents[0] = page1Content;//文章的第一页内容
//            ArticleContent page2Content = new ArticleContent();
//            page2Content.setContent("这是第二页里面的内容：这是一条用于测试webService对接-新增文章！请不必惊慌！<img src=\"/_ueditor/themes/default/images/icon_pdf.gif\" /><a href=\"/_tempxx/Apache反向代理.pdf\" sudyfile-attr=\"{'title':'Apache反向代理.pdf'}\">Apache反向代理.pdf</a>");
//            contents[1] = page2Content;//文章的第二页内容
//            articleSO.setFetchArticleContent(contents);
//            articleSO.setAttachmentMap(new ArrayList<>());
//
//            //设置文章创建人名称
//            User user = new User();
//            user.setName("张三");
//
//            Object[] obj = { loginToken, domainId,user,folderId,articleSO};
//            Long invoke = (Long)call.invoke(obj);
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
//        return Result.ok("同步文章成功！");
//    }


    String APP_ID = "DNDX";
//    String PRIVATE_KEY = "DNDX91b5d691-1f1c-9d46-0428-feed0fa2fa3e";
    String PRIVATE_KEY = "DNDXfd945336-d18e-49e9-95a9-7d909dd433f6";

    String DEFAULT_CHARSET = "UTF-8";
    String[] hexDigits = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C",
            "D", "E", "F"};


    public static void main(String[] args) throws Exception {
        ArticleDataController articleDataController = new ArticleDataController();
        System.out.println(articleDataController.encryptSecureToken());
    }
    String encryptSecureToken() throws Exception {
        Calendar cal = Calendar.getInstance();
        long currentTime = cal.getTimeInMillis();
        String nonceStr = getRandomStr();//获取随机数
        String signature = sign(nonceStr, String.valueOf(currentTime));
        JSONObject json = new JSONObject();
        json.put("signType","MD5");
        json.put("appName",APP_ID);
        json.put("timeStamp", currentTime);
        json.put("nonce", nonceStr);
        json.put("signature", signature);
//        String token = BASE64Coder.encode(json.toJSONString().getBytes(DEFAULT_CHARSET));
        String token = new BASE64Encoder().encode(json.toJSONString().getBytes(DEFAULT_CHARSET));
        //String secureTokenStr = new String(token);
        return "[newSecurity]"+token.replaceAll("\r|\n", "");
//        return token.replaceAll("\r|\n", "");
    }

    /**
     * 生成16位随机数
     */
    String getRandomStr() {
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 16; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }


    String sign(String nonceStr, String timeStamp) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        Object[] signParams = new Object[]{nonceStr, timeStamp, APP_ID, PRIVATE_KEY};
        Arrays.sort(signParams);
        String tempStr = new StringBuilder().append(signParams[0]).append(signParams[1]).append(signParams[2]).append(signParams[3]).toString();
        out.println(tempStr);
        //String signature = EncryptUtil.encodeByMD5(tempStr);
        String signature = encodeByMD5(tempStr);
        return signature;
    }

    /**
     * MD5加密
     */
    String encodeByMD5(String originstr) {
        if (originstr != null) {
            try {
                // 创建具有指定算法名称的信息摘要
                MessageDigest md = MessageDigest.getInstance("MD5");
                // 使用指定的字节数组对摘要进行最后的更新，然后完成摘要计算
                md.update(originstr.getBytes(DEFAULT_CHARSET));
                return getFormattedText(md.digest());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        //把密文转换成十六进制的字符串
        for(int j = 0; j < len; j++) {
            buf.append(hexDigits[(bytes[j] >> 4) & 0x0f]);//高位
            buf.append(hexDigits[bytes[j] & 0x0f]);//低位
        }
        return buf.toString();
    }


}
